package com.xs.server.handler;

import java.util.HashMap;
import java.util.Map;

import org.apache.log4j.Logger;

import com.alibaba.fastjson.JSON;
import com.xs.entity.LonginEntity;
import com.xs.entity.Message;

import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;

public class ServerHandler extends ChannelInboundHandlerAdapter {

	private Map<String,ChannelHandlerContext> routeMap = new HashMap<String,ChannelHandlerContext>();
	
	private static final Logger logger = Logger.getLogger(ServerHandler.class);
	
	@Override
	public void channelActive(ChannelHandlerContext ctx) throws Exception {
		logger.info("连接已经建立：" + ctx.channel());
	}

	@Override
	public void channelRead(final ChannelHandlerContext ctx, Object msg) throws Exception {
		logger.info("服务器收到消息内容为：" + msg);

		if(msg.toString().contains("loninFlag")){
			
			LonginEntity loginMsg =  JSON.parseObject(msg.toString(),LonginEntity.class);
			
			routeMap.put(loginMsg.getUserName(), ctx);
			
			ctx.writeAndFlush(loginMsg.getUserName()+":已登录***"+"\r\n");
			
			return ;
		}
		
		
		Message recieveMsge =  JSON.parseObject(msg.toString(),Message.class);
		
		String targetName = recieveMsge.getTargetName();
		
		ChannelHandlerContext targetChannel = routeMap.get(targetName);
		
		if(targetChannel!=null){
			targetChannel.writeAndFlush("userName:" + recieveMsge.getUserName() + 
					"content:"+ recieveMsge.getContent()+"\r\n");
		}
		else{
			ctx.writeAndFlush("userName:" + recieveMsge.getTargetName() + 
					"不在线\r\n");
		}
	
		
		//ch.writeAndFlush(JSON.toJSONString(msg)+"\r\n");
		//ChannelFuture channel = ctx.writeAndFlush("服务器说：" + msg +"\r\n");
	}

	@Override
	public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
		cause.printStackTrace();
		/*if(ctx!=null){
			ctx.close();
		}*/
		logger.error(cause);
		
	}
	

	
	
}
